import 'package:flutter/material.dart';
import '../model/playing_card.dart';
import '../components/static_playingcard.dart';
import '../model/player.dart';

import '../blocs/room_bloc.dart';
import '../blocs/bloc_provider.dart';
import './view_role.dart';
import 'dart:math' as Math;
import '../static_var.dart';
import '../blocs/other_role_bloc.dart';

class ViewOtherrole<T extends RoomBloc> extends StatelessWidget with ViewRole {
  String roleId;
  RoomBloc bloc;
  bool isRight;
  Widget thisWidget;

  final Color operateTextColor = StaticVar.yellowColor;
  ViewOtherrole({@required this.roleId, this.isRight=false}):super(key: Key(roleId));

  void setPos(bool isRight) {
    this.isRight = isRight;
  }
   Widget getOperateText(String text) {
    return Text(text, style: TextStyle(color: operateTextColor, fontWeight: FontWeight.w600, fontSize: 15));
  }
  Widget getCardsList(List cardTexts, {bool isSmall = false}) {
    double divideDis = isSmall ? 10 : 15;
    int maxRowCount = 10;
    double cardsWidgetsWidth = divideDis * (Math.min(cardTexts.length, maxRowCount) - 1) + (isSmall?PlayingCard.cardWidth3:PlayingCard.cardWidth2);
    double startPosLeft = 0;

    List<Widget> cardWidgets = [];
    int cardIndex = 0;
    double secondRowTop = (isSmall ? PlayingCard.cardHeight3 : PlayingCard.cardHeight2) / 2;
    cardTexts.forEach((cardText){
      if(cardIndex >= maxRowCount) {
        cardWidgets.add(Positioned(
          top: secondRowTop,
          left: startPosLeft,
          child: StaticPlayingCard(PlayingCard(cardText: cardText,sizeType: isSmall ? 3 : 2)),
        ));
        startPosLeft += divideDis;
      }else {
        cardWidgets.add(Positioned(
          left: startPosLeft,
          child: StaticPlayingCard(PlayingCard(cardText: cardText,sizeType: isSmall ? 3 : 2)),
        ));
        startPosLeft += divideDis;
        if(cardIndex + 1 == maxRowCount) {
          startPosLeft = 0;
        }
      }
      cardIndex ++;
    });
    return Container(
      width: cardsWidgetsWidth,
      height: isSmall ? PlayingCard.cardHeight3 : PlayingCard.cardHeight2,
      child: Stack(
        overflow: Overflow.visible,
        children: cardWidgets,
      )
    );
  }
  Widget getCardCount() {
    OtherRoleBloc currentOtherRoleBloc = bloc.getOtherRoleBloc(roleId);
    return StreamBuilder<Map>(
      stream: currentOtherRoleBloc.signStream,
      initialData: currentOtherRoleBloc.signData,
      builder: (BuildContext context, AsyncSnapshot<Map> snapshotIsLandlord) {
        bool roleIsLandlord = snapshotIsLandlord.data['isLandlord'];
        return StreamBuilder<List>(
          stream: currentOtherRoleBloc.cardsStreamStream,
          initialData: currentOtherRoleBloc.cardsData,
          builder: (BuildContext context, AsyncSnapshot<List> snapshot){
            List cardsData = snapshot.data;
            if(cardsData.length > 0 && cardsData[0] != '') {  //明牌或游戏结束
              return getCardsList(cardsData, isSmall: true);
            }else {
              return Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  StaticPlayingCard(PlayingCard.coverd(sizeType:3, isLandLord: roleIsLandlord)),
                  Stack(
                    children: <Widget>[
                      Positioned(
                        child: Text(cardsData.length.toString()+'张', style: TextStyle(fontSize: 12, color: Colors.white))
                      )
                    ]
                  )
                ]
              );
            }
          }
        );
      }
    );
  }

  Widget getCardBody() {
    return StreamBuilder<Map>(
      stream: this.bloc.getOtherRoleBloc(this.roleId).statusStream,
      initialData: this.bloc.getOtherRoleBloc(this.roleId).statusData,
      builder: (BuildContext context, AsyncSnapshot<Map> snapshot){
        Widget widget;
        PlayerStatus status = snapshot.data['status'];
        switch (status) {
          case PlayerStatus.ready:
            Widget cardHand = Icon(IconData(0xe79f, fontFamily: 'iconfont'), color: Colors.white);
            widget = this.isRight ? cardHand : Container(
              margin: EdgeInsets.only(left: 18),
              child: Container(
                transform: Matrix4.identity()..rotateY(Math.pi),
                child: cardHand,
              ),
            );
            break;
          case PlayerStatus.callLandlord:
            widget = this.getOperateText('叫地主');
            break;
          case PlayerStatus.notLandlord:
            widget = this.getOperateText('不叫');
            break;
          case PlayerStatus.robLandlord:
            widget = this.getOperateText('抢地主');
            break;
          case PlayerStatus.notRobLandlord:
            widget = this.getOperateText('不抢');
            break;
          case PlayerStatus.waiting:
            List lastCards = snapshot.data['lastCards'];
            if(lastCards != null && lastCards.length > 0) {
              widget = getCardsList(lastCards);
            }else {
              widget = getOperateText('不要');
            }
            break;
          default: 
            widget = Container();
            break;
        }
        if(status != PlayerStatus.notReady && status != PlayerStatus.ready && status != PlayerStatus.emptyStatus) {
          widget = this.isRight ? Row(
            children: <Widget>[
              widget,
              Container(width: 8),
              this.getCardCount()
            ],
          ):Row(
            children: <Widget>[
              this.getCardCount(),
              Container(width: 8),
              widget
            ],
          );
        }
        return widget;
      }
    );
  }


  @override
  Widget build(BuildContext context) {
    this.bloc = BlocProvider.of<T>(context);

    Widget playerSign = Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: <Widget>[
        getAvatar<OtherRoleBloc>(playerId: this.roleId, roleBloc: this.bloc.getOtherRoleBloc(this.roleId))
      ],
    );
    return Row(
      children: isRight ? <Widget>[
        getCardBody(),
        playerSign
      ]:<Widget>[
        playerSign,
        getCardBody()
      ],
    );
  }
}